import { t } from '@/components/utils';
import { DownOutlined, ReloadOutlined, SearchOutlined, UpOutlined } from '@ant-design/icons';
import {
  ProFormDatePicker,
  ProFormDateRangePicker,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  QueryFilter,
} from '@ant-design/pro-components';
import { Button, Col, Row, Space } from 'antd';
import { useRef, useState } from 'react';
import type { SearchFieldConfig, SearchFormProps } from '../types';

const SearchForm: React.FC<SearchFormProps> = ({ fields, initialValues, onSearch, onReset }) => {
  const formRef = useRef<any>();
  const [searchValues, setSearchValues] = useState<Record<string, any>>(initialValues || {});

  // 筛选可见字段并处理动态选项
  const getVisibleFields = (values: Record<string, any>) => {
    return fields
      .filter((field) => {
        // 判断字段是否可见
        if (field.visible === undefined) return true;
        if (typeof field.visible === 'boolean') return field.visible;
        if (typeof field.visible === 'function') return field.visible(values);
        return true;
      })
      .map((field) => {
        // 处理动态选项
        if (field.dynamicOptions && typeof field.dynamicOptions === 'function') {
          return {
            ...field,
            options: field.dynamicOptions(values),
          };
        }
        return field;
      });
  };

  const visibleFields = getVisibleFields(searchValues);

  // 当字段数量超过4个时启用折叠功能
  const shouldCollapse = visibleFields.length > 4;
  const defaultCollapsed = shouldCollapse;

  const renderField = (field: SearchFieldConfig) => {
    const commonProps: SearchFieldConfig['props'] = {
      name: field.name,
      label: field.label,
      placeholder: field.placeholder,
      rules: field.required
        ? [
            { required: true, message: `请${field.type === 'select' ? '选择' : '输入'}${field.label}` },
            ...(field.rules || []),
          ]
        : field.rules,
      ...field.props,
    };

    switch (field.type) {
      case 'input':
        return (
          <ProFormText
            key={field.name}
            {...commonProps}
            allowClear
            fieldProps={{
              className: 'search-form-field',
              ...commonProps.fieldProps,
            }}
          />
        );

      case 'select':
        return (
          <ProFormSelect
            key={field.name}
            {...commonProps}
            options={field.options}
            allowClear
            fieldProps={{
              className: 'search-form-field',
              ...commonProps.fieldProps,
            }}
          />
        );

      case 'dateRange':
        return (
          <ProFormDateRangePicker
            key={field.name}
            {...commonProps}
            fieldProps={{
              className: 'search-form-field',
              ...commonProps.fieldProps,
            }}
          />
        );

      case 'date':
        return (
          <ProFormDatePicker
            key={field.name}
            {...commonProps}
            fieldProps={{
              className: 'search-form-field',
              ...commonProps.fieldProps,
            }}
          />
        );

      case 'number':
        return (
          <ProFormDigit
            key={field.name}
            {...commonProps}
            fieldProps={{
              className: 'search-form-field',
              ...commonProps.fieldProps,
            }}
          />
        );

      case 'textarea':
        return (
          <ProFormTextArea
            key={field.name}
            {...commonProps}
            fieldProps={{
              className: 'search-form-field',
              ...commonProps.fieldProps,
            }}
          />
        );

      default:
        return (
          <ProFormText
            key={field.name}
            {...commonProps}
            allowClear
            fieldProps={{
              className: 'search-form-field',
              ...commonProps.fieldProps,
            }}
          />
        );
    }
  };

  const handleValuesChange = (changedValues: Record<string, any>, allValues: Record<string, any>) => {
    setSearchValues(allValues);
  };

  const handleFinish = async (values: Record<string, any>) => {
    // 检查必填字段（仅检查可见字段）
    const currentVisibleFields = getVisibleFields(values);
    const requiredFields = currentVisibleFields.filter((field) => field.required);
    const missingFields = requiredFields.filter((field) => {
      const value = values[field.name];
      return value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0);
    });

    if (missingFields.length > 0) {
      // 如果有必填字段未填写，触发表单验证
      try {
        await formRef.current?.validateFields();
      } catch (error) {
        // 验证失败，阻止搜索
        return;
      }
    }

    onSearch(values);
  };

  const handleReset = () => {
    formRef.current?.resetFields();
    setSearchValues(initialValues || {});
    onReset();
  };

  return (
    <div className="search-form">
      <QueryFilter
        formRef={formRef}
        initialValues={initialValues}
        onFinish={handleFinish}
        onReset={handleReset}
        onValuesChange={handleValuesChange}
        labelWidth="auto"
        span={{
          xs: 24,
          sm: 12,
          md: 12,
          lg: 8,
          xl: 6,
          xxl: 6,
        }}
        defaultCollapsed={defaultCollapsed}
        collapseRender={(collapsed) =>
          shouldCollapse ? (
            collapsed ? (
              <>
                <DownOutlined style={{ marginRight: 4 }} />
                {t('common', 'expanded')}
              </>
            ) : (
              <>
                <UpOutlined style={{ marginRight: 4 }} />
                {t('common', 'unexpanded')}
              </>
            )
          ) : (
            false
          )
        }
        className="search-form-query-filter"
        submitter={{
          render: (props, dom) => {
            return (
              <Row justify="end" className="search-form-actions">
                <Col>
                  <Space size="small">
                    <Button
                      type="primary"
                      icon={<SearchOutlined />}
                      onClick={() => {
                        props.form?.submit();
                      }}
                      className="search-form-search-btn"
                    >
                      {t('common', 'search')}
                    </Button>
                    <Button
                      icon={<ReloadOutlined />}
                      onClick={() => {
                        props.form?.resetFields();
                        setSearchValues(initialValues || {});
                        onReset();
                      }}
                      className="search-form-reset-btn"
                    >
                      {t('common', 'reset')}
                    </Button>
                  </Space>
                </Col>
              </Row>
            );
          },
        }}
      >
        {visibleFields.map(renderField)}
      </QueryFilter>
    </div>
  );
};

export default SearchForm;
